#include "Job.h"
#include <vector>
#include <iostream>

class Tasks{
	public:
		Tasks(char* pattern, int _passwordLength){
			this->passwordLength = _passwordLength;
		
			int jobsCount = strlen(pattern);
			int i;	
	
			for(i=0; i<(jobsCount-1); i++){
				Job j;
				j.id = i;
				j.isFinished=0;
				j.sentToNodeId=-1;
				j.success=0;
				j.startTime=0;
				j.endTime=0;
				_fillStringByDigit(j.rangeFrom, pattern[i], passwordLength);
				_fillStringByDigit(j.rangeTo, pattern[i+1], passwordLength);
				_fillStringByDigit(j.foundPassword, 0, passwordLength);
				j.pattern = pattern;
				tasksList.push_back(j);
			}
		};

		void PrintJob(Job *job){
			printf("ID:%d | Fin: %d | Succ: %d | NOD: %d | T: %ds | FR: %s | TO: %s | PWD: %s\n",
						job->id,
						job->isFinished, job->success, job->sentToNodeId, job->endTime-job->startTime,
						job->rangeFrom, job->rangeTo,
						job->foundPassword);
		}

		void PrintJobs(){
			int size=tasksList.size();
			for(int i=0; i<size; i++){
				PrintJob(&tasksList[i]);
			}
		}
	
		Job* FindJob(int id){
			int size=tasksList.size();
			for(int i=0; i<size; i++){
				if (tasksList[i].id==id)
					return &tasksList[i];
			}
		}

		void Update(Job *j){
			Job *currentJob = FindJob(j->id);
			memcpy(currentJob, j, sizeof(Job));
		}

		bool AreFinished(){
			int size=tasksList.size();
			int incomplete=0;
			for(int i=0; i<size; i++){
				if (tasksList[i].isFinished==0)
					return false;
			}
			return true;
		}

		bool IsPasswordFound(){
			int size=tasksList.size();
			for(int i=0; i<size; i++){
				if (tasksList[i].success==true) 
					return true;
			}
			return false;
		}

		Job GetUnusedJobForNode(int nodeId){
			int size=tasksList.size();
			for(int i=0; i<size; i++){
				if (tasksList[i].sentToNodeId==-1) {
					tasksList[i].sentToNodeId=nodeId;
					return tasksList[i];
				}
			}
		}		

		
	private:
		int passwordLength;
		char *pattern;
		std::vector<Job> tasksList;

		void _fillStringByDigit(char inputStr[], char digit, int length){	
			memset(inputStr, (int)digit, length);
			inputStr[length] = 0;
		}
};
